package com.weibo.click;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;



public class EBookGenerator {
	private static final String pathTemplates = "c:/java/files/templates";
	private static final String path = "c:/java/files/templates";
	private static final String confPath = "c:/java/files/conf";
	private final String toker = ";";


	/* 创建最后用于发送的真相文件 */
	public void createSendMessages() {
		Object[] msgs = InMemJobServices.getInstance().msgMap.values()
				.toArray();
		Object[] bookLinks = (Object[]) InMemJobServices.getInstance().bookLink
				.toArray();
		int otherInfoCount=0;
		for (int x1 = 0; x1 < msgs.length; x1++) {
			for (int x2 = 0; x2 < bookLinks.length; x2++) {
				BookLink book = (BookLink) bookLinks[x2];
				int prop = book.getProp();
				String link = book.getBookLink();
				String msgTemplate = new String(msgs[x1].toString());
				for (int k = 0; k < prop; k++) {
					String finalmsg=new String(msgTemplate);
					finalmsg= new String(finalmsg.replaceFirst("#link#",
							link));
					while (finalmsg.indexOf("#info#") != -1) {
						otherInfoCount++;//通过累加求mod的方法保证每个插入的info链接都能被逐次的均匀call
						String other = InMemJobServices.getInstance()
								.getRandomOtherInfo(otherInfoCount);
						//System.out.println("otherInfoCount="+otherInfoCount+"---"+"other=="+other);
						finalmsg = new String(finalmsg.replaceFirst(
								"#info#", other + " "));
					}
					int hash = finalmsg.hashCode();
					// 把生成的真相字符串放入内存HashMap
					String key = "X" + k + "_" + hash;
					//(new String(finalmsg));
					InMemJobServices.getInstance().allSendMessages.put(key,
							new String(finalmsg));
				}
			}

		}
	}

	/**
	 * @param msgTemplate
	 * @param key
	 */
	private void writeTruthFiles(String msgTemplate, String key) {
		OutputStreamWriter writer = null;
		BufferedWriter bufWriter = null;
		try {

			writer = new OutputStreamWriter(new FileOutputStream(new File(path
					+ "/" + key + ".txt")), "UTF-8");
			bufWriter = new BufferedWriter(writer);
			writer.write(msgTemplate);
		} catch (FileNotFoundException e) {
			// System.out.println(e);
		} catch (IOException e) {
			// System.out.println(e);
		} finally {
			try {
				writer.flush();
				writer.close();
				bufWriter.close();
			} catch (IOException e) {
				// System.out.println(e);
			}
		}// try
	}

	/* 从真相文本文件中获取信息 */
	public void collectTruthMsgFromFiles() {
		try {

			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith(".txt");
				}
			};

			File folder = new File(pathTemplates);
			File[] listOfFiles = folder.listFiles(filter);
			String s = "";

			for (int i = 0; i < listOfFiles.length; i++) {
				String name = listOfFiles[i].getName();
				String sendMsg = "";// 用于发送的message，从文件读取
				InputStreamReader rd = new InputStreamReader(
						new FileInputStream(listOfFiles[i]), "UTF-8");

				// FileReader rd=new FileReader(listOfFiles[i]);
				// System.out.println("rd.getEncoding()="+rd.getEncoding());
				BufferedReader in = new BufferedReader(rd);
				while ((s = in.readLine()) != null) {
					// String UTF8Str = new String(s.getBytes(),"UTF-8");
					sendMsg += s + "\n";
				}
				// sendMsg=sendMsg.substring(0, sendMsg.length()-2);
				rd.close();
				in.close();
				if (sendMsg.trim().length() <= 2) {
					InMemJobServices.getInstance().delEmptyMsgFile(name);

					boolean flg = listOfFiles[i].delete();// 从缓冲中删除空文件
					// System.out.println(name+" has been deleted from Memory");
					// System.out.println(listOfFiles[i].getName()+" deleted status is : "+flg);
					// System.out.println(name+"has been deleted");
				} else {
					InMemJobServices.getInstance()
							.addMsgFromFile(name, sendMsg);
					// System.out.println(name+"has been added into buffer ");
					// System.out.println("Contents of truth file are "+new
					// String(sendMsg.getBytes(),"UTF-8"));
				}
				// String
				// sendText=InMemJobServices.getInstance().retriveRandomTruthFileFromBuffer();
				String sendContents = new String(sendMsg.getBytes(), "UTF-8");
				// System.out.println("sendContents are "+sendContents);
			}// for
			/************************ 处理数据库的消息 ***********************************/
		} catch (FileNotFoundException e) {
			//System.out.println(e);
		} catch (IOException e) {
			//System.out.println(e);
		}
		return;
	}

	/**
	 * 电子书的链接允许重复
	 */
	public void loadBookLinksFromFiles() {
		InputStreamReader rd = null;
		BufferedReader in = null;

		try {
			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith("bookLink.txt");
				}
			};

			File folder = new File(confPath);
			File[] listOfFiles = folder.listFiles(filter);
			String s = "";
			String link = "", prop = "1";// prop是整数，为以后的复杂的算法做准备，每个book的链接可以给予不同的权重
			rd = new InputStreamReader(new FileInputStream(listOfFiles[0]),
					"UTF-8");
			in = new BufferedReader(rd);
			while ((s = in.readLine()) != null) {
				if (s.trim().length() <= 1) {
					break;
				}
				StringTokenizer fenxi = new StringTokenizer(s, toker); // 空格和逗号做分
				try {
					link = fenxi.nextToken().trim();// 解析link
				} catch (NoSuchElementException e) {
					continue;
				}
				try {
					prop = fenxi.nextToken();// 解析占用标志
				} catch (NoSuchElementException e) {
					prop = "1";
				}
				// System.out.println("开始加载保存的book链接......");
				if (link == null || link.trim().equals("") || prop == null
						|| prop.trim().equals("")) {
					return;
				} else {
					BookLink book = new BookLink();
					book.setBookLink(link.trim());
					book.setProp(Integer.parseInt(prop.trim()));
					InMemJobServices.getInstance().bookLink.add(book);
					// System.out.println(link+toker+flag);
				}
			}// while
		} catch (FileNotFoundException e) {
			//logger.error(e);
		} catch (IOException e) {
			//logger.error(e);
		} finally {
			try {
				rd.close();
				in.close();
			} catch (IOException e) {
				//logger.error(e);
			}
		}
		return;
	}

	/* 问候信息，插入真相文件 */
	public void loadOtherInfoFromFiles() {
		InputStreamReader rd = null;
		BufferedReader in = null;

		try {
			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith("otherInfo.txt");
				}
			};

			File folder = new File(confPath);
			File[] listOfFiles = folder.listFiles(filter);
			String s = "";
			rd = new InputStreamReader(new FileInputStream(listOfFiles[0]),
					"UTF-8");
			in = new BufferedReader(rd);
			while ((s = in.readLine()) != null) {
				if (s.trim().length() <= 1) {
					break;
				}
				InMemJobServices.getInstance().otherInfo.put(
						"other_" + s.hashCode(), s);
			}// while
		} catch (FileNotFoundException e) {
			// System.out.println(e);
		} catch (IOException e) {
			// System.out.println(e);
		} finally {
			try {
				rd.close();
				in.close();
			} catch (IOException e) {
				// System.out.println(e);
			}
		}
		return;
	}

	public static void main(String[] args) {
		EBookGenerator gen = new EBookGenerator();
		gen.loadBookLinksFromFiles();
		gen.loadOtherInfoFromFiles();
		gen.collectTruthMsgFromFiles();
		gen.createSendMessages();

	}
}
